/**
 * 	 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *   @author Colin Redmond
 *   Copyright (C) 2011 Colin Redmond
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package com.cred.industries.platform.dao {
	import com.adobe.net.URI;
	import com.cred.industries.platform.business.object.CustomerBO;
	import com.cred.industries.platform.dao.event.SessionDAOEvent;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import org.httpclient.HttpClient;
	import org.httpclient.HttpRequest;
	import org.httpclient.events.HttpDataEvent;
	import org.httpclient.events.HttpDataListener;
	import org.httpclient.events.HttpResponseEvent;
	import org.httpclient.events.HttpStatusEvent;
	import org.httpclient.http.Delete;
	import org.iotashan.oauth.IOAuthSignatureMethod;
	import org.iotashan.oauth.OAuthConsumer;
	import org.iotashan.oauth.OAuthRequest;
	import org.iotashan.oauth.OAuthSignatureMethod_HMAC_SHA1;
	
	[Event(name="SESSION_CREATED", type="com.cred.industries.dao.event.SessionDAOEvent")]
	[Event(name="SESSION_LOGGED_OUT", type="com.cred.industries.dao.event.SessionDAOEvent")]
	[Event(name="SESSION_FAILED", type="com.cred.industries.dao.event.SessionDAOEvent")]  

	/**
	 * @author Colin Redmond
	 * Copyright 2011
	 **/
	public final class SessionDAO extends EventDispatcher {
	
		private static var mSessionPath:String = "session";
		
		private var mData:ByteArray = null;
		
		private var mStatusCode:int = 0;
		
		public function SessionDAO() { }
		
		public function authenticate(customer:CustomerBO):void {
			
			var client:HttpClient = new HttpClient();
			
			var listener:HttpDataListener = new HttpDataListener();
			listener.onStatus = statusHandler;
			listener.onDataComplete =  dataCompleteHandler;
			listener.onComplete = sessionCreateCompleteHandler;
			listener.onError = errorHandler;
			client.listener = listener;
			
			var oAuthConsumer:OAuthConsumer = new OAuthConsumer(customer.personaName, customer.password);
			var signMethod:IOAuthSignatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
			var oAuthRequest:OAuthRequest = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_POST, ServerDAODefines.serverURL +  mSessionPath, null, oAuthConsumer);
			
			var urlString:String = oAuthRequest.buildRequest(signMethod);
			var uri:URI = new URI(urlString);

			client.post(uri, new ByteArray());
		}
		
		public function logOut(sessionId:String):void {
			
			var client:HttpClient = new HttpClient();
			
			var listener:HttpDataListener = new HttpDataListener();
			listener.onStatus = statusHandler;
			listener.onDataComplete =  dataCompleteHandler;
			listener.onComplete = logoutCompleteHandler;
			listener.onError = errorHandler;

			var uri:URI = new URI(ServerDAODefines.serverURL +  mSessionPath + "/" + sessionId);
			var request:HttpRequest = new Delete();
			request.addHeader("sessionid", sessionId);
			
			client.listener = listener;
			client.request(uri, request);
		}
		
		private function sessionCreateCompleteHandler(event:HttpResponseEvent):void {
			
			if(mStatusCode == 200 || mStatusCode == 201) {
				var sessionXML:XML = new XML(mData);
				dispatchEvent(new SessionDAOEvent(SessionDAOEvent.SESSION_CREATED, sessionXML));
			} else {
				dispatchEvent(new SessionDAOEvent(SessionDAOEvent.SESSION_FAILED, null, "Unable to log in, check your name and password and try again"));
			}
		}
		
		private function logoutCompleteHandler(event:HttpResponseEvent):void {
			
			if(mStatusCode == 200 || mStatusCode == 201) {
				dispatchEvent(new SessionDAOEvent(SessionDAOEvent.SESSION_CREATED));
			} else {
				dispatchEvent(new SessionDAOEvent(SessionDAOEvent.SESSION_FAILED));
			}
		}
		
		private function errorHandler(event:ErrorEvent):void {
			
			trace( "SessionDAO Had problem connecting. " + event.toString() );
			dispatchEvent(new SessionDAOEvent(SessionDAOEvent.SESSION_FAILED, null, "Server did not respond. Please have the server administrator check the server")); 
		}
		
		private function dataCompleteHandler(event:HttpResponseEvent, data:ByteArray):void {
			
			trace("SessionDAO data " + data.toString());
			mData = data;
		}
		
		private function statusHandler(event:HttpStatusEvent):void {
			
			trace("SessionDAO HTTPStatusEvent " + event.response.code); 
			mStatusCode = int(event.response.code);
		}
	}
}